<?php
namespace Admin\Controller;
use Think\Page;

/**
 * 站点管理后台内容控制器
 */
class SitesController extends AdminController {
    private $cat_id        =   null; //文档分类id

    public function add($model = 4){
        //获取模型信息
        $model = M('Model')->where(array('status' => 1))->find($model);
        $model || $this->error('模型不存在！');
        if(IS_POST){
            $Model  =   D(parse_name(get_table_name($model['id']),1));
            // 获取模型的字段信息
            $Model  =   $this->checkAttr($Model,$model['id']);
            if($Model->create() && $Model->add()){
                $this->success('添加'.$model['title'].'成功！', U('index'));
            } else {
                $this->error($Model->getError());
            }
        } else {

            $fields = get_model_attribute($model['id']);

            $this->assign('model', $model);
            $this->assign('fields', $fields);
            $this->meta_title = '新增'.$model['title'];
            $this->display('Think:add');
        }
    }

    public function edit($model = 4, $id = 0){
        //获取模型信息
        $model = M('Model')->find($model);
        $model || $this->error('模型不存在！');

        if(IS_POST){
            $Model  =   D(parse_name(get_table_name($model['id']),1));
            // 获取模型的字段信息
            $Model  =   $this->checkAttr($Model,$model['id']);
            if($Model->create() && $Model->save()){
                $this->success('保存'.$model['title'].'成功！', U('index'));
            } else {
                $this->error($Model->getError());
            }
        } else {
            $fields     = get_model_attribute($model['id']);

            //获取数据
            $data       = M(get_table_name($model['id']))->find($id);
            $data || $this->error('数据不存在！');

            $this->assign('model', $model);
            $this->assign('fields', $fields);
            $this->assign('data', $data);
            $this->meta_title = '编辑'.$model['title'];
            $this->display('Think:edit');
        }
    }

    /**
     * 显示左边菜单，进行权限控制
     */
    protected function getMenu(){
        //获取动态分类
        $cate       =   M('Cat')->where(array('status'=>1))->field('id,title,pid,sort')->order('pid,sort')->select();
        $cate           =   list_to_tree($cate);    //生成分类树
        //获取分类id
        $cat_id        =   I('param.cat_id');
        $this->cat_id  =   $cat_id;

        //是否展开分类
        $hide_cate  =   true;

        //生成每个分类的url
        foreach ($cate as $key=>&$value){
            $value['url']   =   'Sites/index?cat_id='.$value['id'];
            if($cat_id == $value['id'] && $hide_cate){
                $value['current'] = true;
            }else{
                $value['current'] = false;
            }
            if(!empty($value['_child'])){
                $is_child = false;
                foreach ($value['_child'] as $ka=>&$va){
                    $va['url']      =   'Sites/index?cat_id='.$va['id'];
                    if(!empty($va['_child'])){
                        foreach ($va['_child'] as $k=>&$v){
                            $v['url']   =   'Sites/index?cat_id='.$v['id'];
                            $v['pid']   =   $va['id'];
                            $is_child = $v['id'] == $cat_id ? true : false;
                        }
                    }
                    //展开子分类的父分类
                    if($va['id'] == $cat_id || $is_child){
                        $is_child = false;
                        if($hide_cate){
                            $value['current']   =   true;
                            $va['current']      =   true;
                        }else{
                            $value['current']   =   false;
                            $va['current']      =   false;
                        }
                    }else{
                        $va['current']      =   false;
                    }
                }
            }
        }
        $this->assign('nodes',      $cate);
        $this->assign('cat_id',    $this->cat_id);
        //获取面包屑信息
        $nav = get_parent_cat($cat_id);
        $this->assign('rightNav',   $nav);
    }

    /**
     * 分类文档列表页
     * @param integer $cate_id 分类id
     * @param integer $model_id 模型id
     * @param integer $position 推荐标志
     * @param integer $group_id 分组id
     */
    public function index($cat_id = null, $model_id = null, $position = null,$group_id=null){
        //获取左边菜单
        $this->getMenu();

        if($cat_id===null){
            $cat_id = $this->cat_id;
        }

        // 获取列表绑定的模型
        $models     =  4;
        $model = M('Model')->getById($model_id);
        $model['list_grid'] = M('Model')->getFieldByName('sites','list_grid');
        $this->assign('model', explode(',', $models));

        //解析列表规则
        $fields =	array();
        $grids  =	preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        foreach ($grids as &$value) {
            // 字段:标题:链接
            $val      = explode(':', $value);
            // 支持多个字段显示
            $field   = explode(',', $val[0]);
            $value    = array('field' => $field, 'title' => $val[1]);
            if(isset($val[2])){
                // 链接信息
                $value['href']  =   $val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
            }
            if(strpos($val[1],'|')){
                // 显示格式定义
                list($value['title'],$value['format'])    =   explode('|',$val[1]);
            }
            foreach($field as $val){
                $array  =   explode('|',$val);
                $fields[] = $array[0];
            }
        }

        // 文档模型列表始终要获取的数据字段 用于其他用途
        $fields[] = 'cat_id';
        // 过滤重复字段信息
        $fields =   array_unique($fields);
        // 列表查询
        $list   =   $this->getSiteList($cat_id,$position,$fields);
        // 列表显示处理
        $list   =   $this->parseDocumentList($list,$model_id);

        $this->assign('model_id',$model_id);
        $this->assign('position',$position);
        $this->assign('list',   $list);
        $this->assign('list_grids', $grids);
        $this->assign('model_list', $model);
        // 记录当前列表页的cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);
        $this->display();
    }

    /**
     * 默认文档列表方法
     * @param integer $cate_id 分类id
     * @param integer $position 推荐标志
     * @param mixed $field 字段列表
     */
    protected function getSiteList($cat_id=0,$position=null,$field=true){
        /* 查询条件初始化 */
        $map = array();
        if(isset($_GET['title'])){
            $map['title']  = array('like', '%'.(string)I('title').'%');
        }
        if(isset($_GET['status'])){
            $map['status'] = I('status');
            $status = $map['status'];
        }else{
            $status = null;
            $map['status'] = array('in', '0,1,2');
        }

        // 构建列表数据
        $sites = M('Sites');

        if(!is_null($position)){
            $map[] = "position & {$position} = {$position}";
        }
        if($cat_id){
            $map['cat_id'] =   $cat_id;
        }
//        dump($map);
        $list = $this->lists($sites,$map,'level ASC,id DESC',$field);
        $this->assign('status', $status);
        $this->meta_title = '站点列表';
        return $list;
    }

    /**
     * 设置一条或者多条数据的状态
     */
    public function setStatus($model='Sites'){
        return parent::setStatus('Sites');
    }

    function settags(){
        $sid=I('get.sid');
        if($sid) {
            $vdao=D('Tagv');
            $all_tags=$vdao->where(array('sid'=>$sid))->select();
            $this->assign('all_tags',$all_tags);

            $dao=M('SitesTags');
            $this->assign('sid', $sid);
            $dao = M('Tags');
            $res = $dao->where(array('level' => 0))->limit('0,25')->select();
            $this->assign('lists', $res);
        }
        $this->display();
    }// end settags

    function gettags(){
        $sid=I('post.sid');
        $vdao=D('Tagv');
        $all_tags=$vdao->where(array('sid'=>$sid))->select();
        $this->assign('all_tags',$all_tags);
        foreach($all_tags as $vo){
            echo "<label style=\"margin: 5px 8px;\"><input type=\"checkbox\" name=\"tags[{$vo['tid']}]\">{$vo['name']}</label>";
        }
        exit;
    }// end gettags

    function settags_add(){
        header('Content-Type:application/json; charset=utf-8');
        $sid=I('post.sid');
        $tid=I('post.tid');
        $res=array();
        $res['status']=0;
        $res['msg']='参数错误';
        if($sid&&$tid){
            $dao=M('SitesTags');
            $data=array();
            $data['sid']=$sid;
            $data['tid']=$tid;
            $dao->add($data,array(),true);
            $res['status']=1;
            $res['msg']='设置成功';
        }
        exit(json_encode($res));
    }// end settags_add

    function tags_del(){
        header('Content-Type:application/json; charset=utf-8');
        $sid=I('post.sid');
        $tid=I('post.tid');
        $res=array();
        $res['status']=0;
        $res['msg']='参数错误';
        if($sid&&$tid) {
            foreach ($tid as $v) {
                $dao = M('SitesTags');
                $data = array();
                $data['sid'] = $sid;
                $data['tid'] = $v;
                $dao->where($data)->delete();
                $res['status'] = 1;
                $res['msg'] = '设置成功';
            }
        }
        exit(json_encode($res));
    }// end tags_del_check
}
